from django.contrib.auth.hashers import make_password
from rest_framework.viewsets import ModelViewSet
from user.tasks import send_mail_task
from user.models import *
from user.serializer import *
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.response import Response

from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        email = request.data.get('email')
        phone = request.data.get('phone')
        print(username, password, email, phone)

        if not all([username, password, email, phone]):
            return Response({'code': '401', 'msg': '信息不完整'})

            # 从redis中获取手机验证码进行校验
        redis_cli = get_redis_connection("img_code")
        redis_phone_num = redis_cli.get(phone).decode()
        if redis_phone_num != request.data.get("code"):
            return Response({"code": 4005, 'msg': "短信验证码错误"}, status=200)

        user_obj = User.objects.create(
            username=username,
            password=make_password(password),
            phone=phone,
        )
        return Response({'code': 200, 'msg': '注册成功'})

    # return Response({'code':400,'msg':'注册失败'})


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        user_obj = User.objects.filter(username=username, password=password).first()

        if user_obj:
            return Response({'code': 200, 'msg': '登陆成功'})

        return Response({'code': 400, 'msg': '登陆失败'})


def jwt_response_payload_handler(token, user=None, request=None):
    """
        自定义登陆返回的信息
        :param token: jwt生成的token值
        :param user: User对象
        :param request: 请求
    """
    return {
        'token': token,
        "username": user.username,
        # "authenticated": True,
        # "role": None,
        'id': user.id,
        'msg': '登录成功',
        # "email": user.email
    }


class CheckUserInfo(APIView):
    """
    用户名或者手机号是否存在
    """

    def post(self, request):
        type = request.data.get("type")

        data = request.data.get("data")

        if not all([type, data]):
            return Response({"code": 4005, "msg": "参数不完整"})

        if type == "username":
            count = User.objects.filter(username=data).count()
        elif type == "phone":
            count = User.objects.filter(phone=data).count()
        else:
            return Response({"code": 4009, "msg": "参数不正确"})

        data = {
            "code": 0,
            'msg': "成功",
            "data": {
                "type": type,
                "count": count
            }
        }

        return Response(data)



class Forgot_Password_View(APIView):
    """
    发送邮箱
    """

    def post(self, request):
        username = request.data.get('username')
        email = request.data.get('email')
        print(username, email)
        if not all([username, email]):
            return Response({"msg": "参数不完整", "code": 400})

        user_obj = User.objects.filter(username=username).first()
        print(user_obj)
        if user_obj:

            send_mail_task.delay(username, email, user_obj.id)

            return Response({"msg": "邮箱发送成功", "code": 200})
        else:
            return Response({'msg': "err"})